<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\AppBaseController;
use EasyWeChat\Foundation\Application;
use App\Models\WechatUser;
use App\Repositories\WechatUserRepository;
use App\Models\WechatUserSession;
use App\Repositories\WechatUserSessionRepository;
use EasyWeChat\Core\Exceptions\HttpException;
use EasyWeChat\Encryption\EncryptionException;

class WechatMiniProgramController extends AppBaseController
{
    private $app;
    private $appOptions = [];
    private $miniProgram;
    private $wechatUserRepository;
    private $wechatUserSessionRepository;

    public function __construct(WechatUserRepository $wechatUserRepo,
        WechatUserSessionRepository $wechatUserSessionRepo,
        Request $request)
    {
        if ($request->input('item_mini_program'))
        {
            $this->appOptions['mini_program'] = [
                'app_id'  => config('wechat.item_mini_program.app_id'),
                'secret'  => config('wechat.item_mini_program.secret'),
                'token'   => config('wechat.item_mini_program.token'),
                'aes_key' => config('wechat.item_mini_program.aes_key')
            ];
        }
        else
        {
            $this->appOptions['mini_program'] = [
                'app_id'  => config('wechat.mini_program.app_id'),
                'secret'  => config('wechat.mini_program.secret'),
                'token'   => config('wechat.mini_program.token'),
                'aes_key' => config('wechat.mini_program.aes_key')
            ];
        }

        $this->app = new Application($this->appOptions);
        $this->miniProgram = $this->app->mini_program;

        $this->wechatUserRepository = $wechatUserRepo;
        $this->wechatUserSessionRepository = $wechatUserSessionRepo;
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'code' => 'required'
        ]);

        try {
            $sessionKey = $this->miniProgram->sns->getSessionKey($request->input('code'));
            Log::info('sessionKey : '.json_encode($sessionKey));
        } catch (HttpException $e) {
            Log::info('get sessionKey fail: '.$e->getMessage());
            return $this->sendError('参数 code 有误');
        }

        $rep = $this->wechatUserSessionRepository->saveSession($sessionKey);
        unset($rep->openid);
        unset($rep->session_key);
        return $this->sendResponse($rep->toArray(), trans('flash.api.retrieve_success', ['model' => 'Wechat User Session']));
    }

    public function updateWxUserInfo(Request $request)
    {
        try {
            $session = $this->checkWeachtMiniProgramLogin($request);
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }

        $this->validate($request, [
            'iv' => 'required',
            'encryptedData' => 'required'
        ]);

        try {
            $userInfo = $this->miniProgram->encryptor->decryptData($session['session_key'], $request->input('iv'), $request->input('encryptedData'));
            if ($userInfo['watermark']['appid'] != $this->appOptions['mini_program']['app_id'])
            {
                Log::info('watermark not wechat.mini_program.app_id');
                return $this->sendError('watermark 中 appid 不符');
            }
        } catch (EncryptionException $e) {
            Log::info('decryptData fail: '.$e->getMessage());
            return $this->sendError('参数 iv 或 encryptedData 有误');
        }

        $this->wechatUserRepository->saveUser($userInfo);
        return $this->sendResponse([], trans('flash.api.update_success', ['model' => 'WechatUser']));
    }
}
